package com.ky.server.main;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.ky.server.util.ConfigConstants;
import com.ky.server.util.PropertiesUtil;

public class KyServerApp {

	//构造静态代码块---解析xml文件
	static {
		String xmlPath=PropertiesUtil.getProperty(ConfigConstants.SERVER_FILES_PATH_KEY);
		String resourcesPath=ConfigConstants.SERVER_REDOURCES_PATH;
		SAXReader saxReader = new SAXReader();
		try {
			Document document = saxReader.read(xmlPath);
			//获取根元素
			Element rootElement = document.getRootElement();
			//判断根元素下是否有子元素
			List<Element> fileElements = rootElement.elements();
			if(fileElements.size()==0) {
				//如果没有子元素，则将本地资源中的文件写入xml文件中
				//创建文件对象
				File parentFile = new File(resourcesPath);
				//获取路径下的所有文件
				File[] files = parentFile.listFiles();
				//循环遍历文件数组
				for (int i=0;i<files.length;i++) {
					Element fileElement = rootElement.addElement("file");
					fileElement.addAttribute("id", i+1+" ");
					fileElement.addElement("name").setText(files[i].getName());
					fileElement.addElement("size").setText(String .format("%.2f", files[i].length()/1024.0));
					fileElement.addElement("path").setText(resourcesPath+"/"+files[i].getName());
				}
				OutputFormat format = OutputFormat.createPrettyPrint();
				format.setEncoding("UTF-8");
				XMLWriter writer = new XMLWriter(new FileWriter(xmlPath), format);
				writer.write(document);
				writer.close();
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	public static void main(String[] args) {

		try {
			ServerSocket serverSocket = new ServerSocket(Integer.parseInt(PropertiesUtil.getProperty(ConfigConstants.SERVER_PORT_KEY)));
			System.out.println("服务器端已启动。。。。。。");
			//循环受理客户端的请求
			while(true) {
				Socket clientSocket = serverSocket.accept();
				//通过子线程处理客户端的请求
				new Thread(new KyServerTaskRunnable(clientSocket));
			}
		} catch (NumberFormatException | IOException e) {
			e.printStackTrace();
		}
		
	}

}
